#include "main.h"
#include "bootscreen.h"
#include "lv_port_jpg.h"
#include "FlashDisk.h"
#include "MassStorage.h"
#include "lv_port_disp.h"
#include "lv_port_indev.h"
#include "board.h"
#include "lcd/peripheral_lcd.h"
#include "synwit_ui_framework/synwit_ui.h"
#include "app_usbmsc.h"
#include "ff.h"
#include "dev_sfc.h"
#include "key.h"
   
#define TAG "app"

static void mount_external_fs();
static void user_init();
    
void on_boot(void)
{    
    // 检测和处理U盘模式
    app_usbmsc_handler();
    
    uart_init();
    
    char ver[48];
    synwit_ui_get_platform_version_name(ver, sizeof(ver));
    printf("2.1QXCJ-V1.0: %s\n", ver);
    
    systick_init();
}

void framework_ready(void)
{
    lv_coord_t hres = synwit_ui_manifest_get_int("peripheral.display.hres", 800);
    lv_coord_t vres = synwit_ui_manifest_get_int("peripheral.display.vres", 480);
    int rotation = synwit_ui_manifest_get_int("peripheral.display.rotation", 0);
    
    lcdc_init();
    peripheral_lcd_init(hres, vres);
    jpeg_init();
    
    //显示开机logo和开机动画
    bootscreen(hres, vres);
    
    // LVGL硬件相关服务初始化
    lv_port_jpeg_init();
    lv_port_disp_init(hres, vres, rotation);
    lv_port_indev_init();
    if(lv_disp_get_hor_res(NULL) >= 1024 ||
        lv_disp_get_ver_res(NULL) >= 1024) {
            _lv_mem_set_deceleration(1);
    }

    // 挂载外部存储器(TF卡、外接U盘)
    mount_external_fs();
    // UI框架准备就绪后，就可以注册各个界面了
    app_register_screens();
    
    // 执行用户自定义的初始化流程
    user_init();
}

bool logo_flag = true;
lv_task_t* main_task = NULL;
static void main_task_handler(struct _lv_task_t* task)
{
//把main tick的处理移到这里
	if(!logo_flag)
	    process_rx();
}


void app_ready(void)
{
    lvgl_layer_init();
    
    bootscreen_cleanup();  //切换到lvgl显存后，再释放动画显存
		main_task = lv_task_create(main_task_handler, 5,LV_TASK_PRIO_HIGH,NULL) ;
}

void main_tick(void)
{
    // 主循环每跑一次，都会触发一次这个函数
}

void SysTick_Handler(void)
{
    swm_inctick();
    lv_tick_inc(1);
}

static synwit_app_callback_t s_app_ops = {
    .framework_ready = framework_ready,
    .app_ready = app_ready,
    .main_tick = main_tick,
};

static void mount_external_fs()
{
    static FATFS sd_fatfs;
    
    int enabled_sd = synwit_ui_manifest_get_int("peripheral.storage.sd", 0);
    if(enabled_sd) {
        f_mount(&sd_fatfs, "sd:", 1);
    }
}

static void user_init()
{
    // TODO: 驱动初始化、app全局变量初始化等代码可以添加在这里。
    //（注意：UI对象的创建、加载等不要加在这里，请在对应的screenXXX.c
    // 内进行UI对象的创建及操作）
	sfc_init();
}


uint32_t SPI_DCache[4096] = {0};  

int main()
{   
		logo_flag = true;
    on_boot();

    // 注意! 初始化代码请添加到user_init()函数中而不是这里。因
    // 为执行到这里时，HMI平台还没启动，如果在这里调用任何LVGL
    // 接口，或"synwit_ui_xxxx"类接口，都无法保证能正常执行。
    
    // 启动HMI平台，这个函数会以阻塞模式运行，不会返回。
	

		////////////////拨轮按键配置////////////////////
		GPIO_Init(GPION, PIN0, 0, 1, 0, 0);			//输入，上拉使能，接KEY
		GPIO_Init(GPIOM, PIN5, 0, 1, 0, 0);			//输入，上拉使能，接KEY
		GPIO_Init(GPIOM, PIN6, 0, 1, 0, 0);			//输入，上拉使能，接KEY
////////////////拨轮按键配置////////////////////

////////////////485使能输出////////////////////
		GPIO_Init(GPIOC, PIN8, 1, 0, 0, 0);
	  GPIO_ClrBit(GPIOC, PIN8);
////////////////485使能输出////////////////////
	
////////////////光敏电阻ADC////////////////////
		ADC_InitStructure ADC_initStruct;
		ADC_SEQ_InitStructure ADC_SEQ_initStruct;
		PORT_Init(PORTD, PIN1,  PORTD_PIN1_ADC1_CH0,  0);		//PD.1  => ADC1.CH0
	
		ADC_initStruct.clk_src = ADC_CLKSRC_HRC_DIV8;
		ADC_initStruct.samplAvg = ADC_AVG_SAMPLE1;
		ADC_initStruct.EOC_IEn = 0;	
		ADC_initStruct.HalfIEn = 0;
		ADC_Init(ADC1, &ADC_initStruct);					//配置ADC
		
		ADC_SEQ_initStruct.channels = ADC_CH1;
		ADC_SEQ_initStruct.trig_src = ADC_TRIGGER_SW;
		ADC_SEQ_initStruct.conv_cnt = 1;
		ADC_SEQ_initStruct.samp_tim = ADC_SAMPLE_1CLOCK;
		ADC_SEQ_Init(ADC1, ADC_SEQ0, &ADC_SEQ_initStruct);
		
		ADC_Open(ADC1);										//使能ADC
		ADC_Calibrate(ADC1);
////////////////光敏电阻ADC////////////////////
		
////////////////蜂鸣器PWM////////////////////
		PWM_InitStructure  PWM_initStruct;
		PORT_Init(PORTM, PIN3,  PORTM_PIN3_PWM1A,   0);
		PWM_initStruct.Mode = PWM_CENTER_ALIGNED;
		PWM_initStruct.Clkdiv = 4;					//F_PWM = 20M/4 = 5M
		PWM_initStruct.Period = 5000;				//5M/10000 = 500Hz，中心对称模式下频率降低到250Hz
		PWM_initStruct.HdutyA =  4900;				//2500/10000 = 25%
		PWM_initStruct.DeadzoneA = 0;				//50/5M = 10us
		PWM_initStruct.IdleLevelA = 0;
		PWM_initStruct.IdleLevelAN= 0;
		PWM_initStruct.OutputInvA = 0;
		PWM_initStruct.OutputInvAN= 0;
		PWM_initStruct.HdutyB =  0;				//7500/10000 = 75%
		PWM_initStruct.DeadzoneB = 0;				//50/5M = 10us
		PWM_initStruct.IdleLevelB = 0;
		PWM_initStruct.IdleLevelBN= 0;
		PWM_initStruct.OutputInvB = 0;
		PWM_initStruct.OutputInvBN= 0;
		PWM_initStruct.UpOvfIE    = 0;
		PWM_initStruct.DownOvfIE  = 0;
		PWM_initStruct.UpCmpAIE   = 0;
		PWM_initStruct.DownCmpAIE = 0;
		PWM_initStruct.UpCmpBIE   = 0;
		PWM_initStruct.DownCmpBIE = 0;
		PWM_Init(PWM1, &PWM_initStruct);
		//PWM_Start(PWM1_MSK);
		//PWM_Stop(PWM1_MSK);
////////////////蜂鸣器PWM////////////////////

		
		TIMR_Init(TIMR4, TIMR_MODE_TIMER, CyclesPerUs, 500, 1);	//每500us钟触发一次中断
		
		TIMR_Start(TIMR4);
    synwit_ui_start(NULL, &s_app_ops);
		

}

static inline void DelayBB(void)
{
	for (int us = 0; us < 60000; us++)
	{
		__NOP();
		__NOP();
		__NOP();
	}
}






unsigned char key = 0x00;
bool key_one_flagA = true;
bool key_one_flagB = true;
bool key_one_flagC = true;
#define KEY_OK_TIME 5*20
uint8_t KEY_OK_count = 0;
uint8_t key_beer_stateA = 0;
uint8_t key_beer_stateB = 0;
uint8_t key_beer_stateC = 0;

uint16_t KEYA_hold_count = 0;
uint8_t KEYA_DX_count = 0;//倒显计数
uint8_t KEYA_DX_count_temp = 0;//倒显计数暂存
uint16_t KEYA_DX_outTime = 0;//释放倒显计数
uint16_t KEYA_DX_uartDelay = 0;//倒显延时再响应UART
uint8_t DX_flag = 0;


uint8_t Beer_sound_level = 1;

uint16_t backlightS_count = 0;//标
bool beer_flag = false;
uint16_t beer_count = 0;
uint16_t beer_count_state = 0;

uint8_t sound_state2_count = 0;

void remember(void)
{
		SPI_DCache[0] = DX_flag;
		SPI_DCache[1] = km_MPH_state;
		SPI_DCache[2] = Beer_sound_level;
		SFC_Erase(0x7FF000,3);
		SFC_Write(0x7FF000, SPI_DCache, 3);
}
					
void TIMR4_Handler(void)
{
	uint32_t chn;
	uint16_t HDuty;
	
	TIMR_INTClr(TIMR4);
/////////////////光敏电阻背光////////////////
	backlightS_count++;
	if(backlightS_count>200)//标
	{
		backlightS_count = 0;
		
		
		ADC_Start(ADC1, ADC_SEQ0);
		while((ADC1->SEQ[0].SR & ADC_SR_EOC_Msk) == 0);
		uint16_t adc_data = ADC_Read(ADC1, ADC_SEQ0, &chn);
		
#if 0
		if(adc_data>MIN_ADC&&adc_data<MAX_ADC)
		{
			HDuty = 1000 - 1000*(adc_data-MIN_ADC)/(MAX_ADC-MIN_ADC);
			PWM_SetHDuty(PWM4,PWM_CH_B,HDuty);
		}
#else
		if(adc_data>MAX_ADC)
		{
			HDuty = 800;
			PWM_SetHDuty(PWM4,PWM_CH_B,HDuty);
		}
		else
		{
			HDuty = 6400;
			PWM_SetHDuty(PWM4,PWM_CH_B,HDuty);
		}
#endif
		//printf("adc_data:%d ,HDuty:%d \r\n", adc_data,HDuty);
	}
/////////////////光敏电阻背光////////////////
	
	if(KEYA_DX_uartDelay>0)
	{
		KEYA_DX_uartDelay++;
		if(KEYA_DX_uartDelay>=500)
		{
	 		KEYA_DX_uartDelay = 0;
			UART_Open(UART0);
		}
		
	}
///////////////////////////2秒后释放倒屏计数事件///////////////////////
	if(KEYA_DX_count>0)
		KEYA_DX_outTime++;
	
	if(KEYA_DX_outTime > 4000)//2秒事件
	{
		  KEYA_DX_outTime = 0;
			if(KEYA_DX_count_temp == KEYA_DX_count)
				KEYA_DX_count = 0;
	}
///////////////////////////2秒后释放倒屏计数事件///////////////////////
	if(GPIO_GetBit(GPION, PIN0) == 0)		//确认按键被按下
	{
		KEY_OK_count++;
		if(KEY_OK_count>KEY_OK_TIME)
		{
			KEY_OK_count = 0;
			if(GPIO_GetBit(GPION, PIN0) == 0)
			{
				KEYA_hold_count++;
				if(KEYA_hold_count==200)//10秒
				{
					key_beer_stateA = 1;
					
					if(km_MPH_state==0)
						km_MPH_state = 1;
					else
						km_MPH_state = 0;
					
					show_flag = 1;
					
					remember();
				}
				
				if(key_one_flagA)
				{
					key_one_flagA = false;
					key_beer_stateA = 1;
					KEYA_DX_count++;
					KEYA_DX_count_temp = KEYA_DX_count;
					KEYA_DX_outTime = 0;
					if(KEYA_DX_count>=5)//连续按5次倒屏
					{
						KEYA_DX_uartDelay = 1;
						UART_Close(UART0);

						
						KEYA_DX_count = 0;
						if(DX_flag)
							DX_flag = 0;
						else
							DX_flag = 1;
						
						remember();
					}
					
					printf("KEY_A : %d , DX_flag : %d \r\n", km_MPH_state,DX_flag);
				}
				
			}
		}
	}
	else
	{
		KEYA_hold_count = 0;
		
		key_one_flagA = true;
	}
		
	if(GPIO_GetBit(GPIOM, PIN5) == 0)		//加按键被按下
	{
		KEY_OK_count++;
		if(KEY_OK_count>KEY_OK_TIME)
		{
			KEY_OK_count = 0;
			if(GPIO_GetBit(GPIOM, PIN5) == 0)
			{
				if(key_one_flagB)
				{
					key_one_flagB = false;
					key_beer_stateB = 1;
					key |= 0x20; 
					
					Beer_sound_level++;
					if(Beer_sound_level>4)
						Beer_sound_level = 4;
					
					PWM_SetHDuty(PWM1,PWM_CH_A,5000-Beer_sound_level*VOICE_LEVEL);
					printf("---KEY_UP : %d\r\n", Beer_sound_level);
					
					remember();
				}
			}
		}
	}
	else
	{
		key_one_flagB = true;
	}
	
	if(GPIO_GetBit(GPIOM, PIN6) == 0)		//减按键被按下
	{
		KEY_OK_count++;
		if(KEY_OK_count>KEY_OK_TIME)
		{
			KEY_OK_count = 0;
			if(GPIO_GetBit(GPIOM, PIN6) == 0)
			{
				if(key_one_flagC)
				{
					key_one_flagC = false;
					key_beer_stateC = 1;
					key |= 0x40; 
					
					Beer_sound_level--;
					if(Beer_sound_level<1)
						Beer_sound_level = 1;
					
					PWM_SetHDuty(PWM1,PWM_CH_A,5000-Beer_sound_level*VOICE_LEVEL);
					printf("---KEY_DOWN : %d\r\n", Beer_sound_level);
					
					remember();
				}
			}
		}
	}
	else
	{
		key_one_flagC = true;
	}
	
	
	if(sound_state==1)
	{
		sound_state2_count = 0;
		beer_count_state = 125;
	}
	else if(sound_state==2)
		beer_count_state = 200;
	else if(sound_state==3)
	{
		sound_state2_count = 0;
		beer_count_state = 1000;
	}
	
	if(sound_state!=0)
	{
		 if(beer_flag)
		 {
				beer_count++;
				if(beer_count>beer_count_state)
				{
					if(sound_state==2)
					{
						sound_state2_count++;
						if(sound_state2_count>5)
							sound_state2_count = 0;
					}
					
					beer_count = 0;
					if(sound_state2_count<2)
						PWM_Start(PWM1_MSK);
					beer_flag = false;
				}
		 }
		 else
		 {
				beer_count++;
				if(beer_count>beer_count_state)
				{
					beer_count = 0;
					PWM_Stop(PWM1_MSK);
					beer_flag = true;
				}
		 }
	}
	else
	{
		///////////////按键音乐////////////////
			if(key_beer_stateA==1)
			{
				PWM_Start(PWM1_MSK);
				key_beer_stateA = 2;
			}
			else if(key_beer_stateA==2)
			{
				beer_count++;
				if(beer_count>20*20)
				{
					beer_count = 0;
					PWM_Stop(PWM1_MSK);
					key_beer_stateA = 0;
				}
			}
			
			if(key_beer_stateB==1)
			{
				PWM_Start(PWM1_MSK);
				key_beer_stateB = 2;
			}
			else if(key_beer_stateB==2)
			{
				beer_count++;
				if(beer_count>20*20)
				{
					beer_count = 0;
					PWM_Stop(PWM1_MSK);
					key_beer_stateB = 0;
				}
			}
			
			if(key_beer_stateC==1)
			{
				PWM_Start(PWM1_MSK);
				key_beer_stateC = 2;
			}
			else if(key_beer_stateC==2)
			{
				beer_count++;
				if(beer_count>20*20)
				{
					beer_count = 0;
					PWM_Stop(PWM1_MSK);
					key_beer_stateC = 0;
				}
			}

		///////////////按键音乐////////////////
	}		
	

}